package com.charging.system.service.impl;

import java.util.List;

import com.charging.common.constant.Constants;
import com.charging.common.exception.UtilException;
import com.charging.common.utils.DateUtils;
import com.charging.system.domain.KxCard;
import com.charging.system.domain.KxUserInfo;
import com.charging.system.mapper.KxCardMapper;
import com.charging.system.mapper.KxUserInfoMapper;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.charging.system.mapper.KxRechargeRecordMapper;
import com.charging.system.domain.KxRechargeRecord;
import com.charging.system.service.IKxRechargeRecordService;

import javax.annotation.Resource;

/**
 * 充值记录Service业务层处理
 *
 * @author charging
 * @date 2024-04-19
 */
@Service
public class KxRechargeRecordServiceImpl implements IKxRechargeRecordService
{

    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private KxRechargeRecordMapper kxRechargeRecordMapper;
    @Resource
    private KxUserInfoMapper kxUserInfoMapper;
    @Resource
    private KxCardMapper kxCardMapper;

    /**
     * 查询充值记录
     *
     * @param rechargeRecordId 充值记录主键
     * @return 充值记录
     */
    @Override
    public KxRechargeRecord selectKxRechargeRecordByRechargeRecordId(Long rechargeRecordId)
    {
        return kxRechargeRecordMapper.selectKxRechargeRecordByRechargeRecordId(rechargeRecordId);
    }

    /**
     * 查询充值记录列表
     *
     * @param kxRechargeRecord 充值记录
     * @return 充值记录
     */
    @Override
    public List<KxRechargeRecord> selectKxRechargeRecordList(KxRechargeRecord kxRechargeRecord)
    {
        return kxRechargeRecordMapper.selectKxRechargeRecordList(kxRechargeRecord);
    }

    /**
     * 新增充值记录
     *
     * @param kxRechargeRecord 充值记录
     * @return 结果
     */
    @Override
    public int insertKxRechargeRecord(KxRechargeRecord kxRechargeRecord)
    {
        kxRechargeRecord.setCreateTime(DateUtils.getNowDate());
        return kxRechargeRecordMapper.insertKxRechargeRecord(kxRechargeRecord);
    }

    /**
     * 修改充值记录
     *
     * @param kxRechargeRecord 充值记录
     * @return 结果
     */
    @Override
    public int updateKxRechargeRecord(KxRechargeRecord kxRechargeRecord)
    {
        kxRechargeRecord.setUpdateTime(DateUtils.getNowDate());
        return kxRechargeRecordMapper.updateKxRechargeRecord(kxRechargeRecord);
    }

    /**
     * 批量删除充值记录
     *
     * @param rechargeRecordIds 需要删除的充值记录主键
     * @return 结果
     */
    @Override
    public int deleteKxRechargeRecordByRechargeRecordIds(Long[] rechargeRecordIds)
    {
        return kxRechargeRecordMapper.deleteKxRechargeRecordByRechargeRecordIds(rechargeRecordIds);
    }

    /**
     * 删除充值记录信息
     *
     * @param rechargeRecordId 充值记录主键
     * @return 结果
     */
    @Override
    public int deleteKxRechargeRecordByRechargeRecordId(Long rechargeRecordId)
    {
        return kxRechargeRecordMapper.deleteKxRechargeRecordByRechargeRecordId(rechargeRecordId);
    }

    @Override
    public void rechargeSuccessAction(KxRechargeRecord kxRechargeRecord) {
        String ucid = kxRechargeRecord.getRechargeRecordId().toString();
        if(ObjectUtils.isNotEmpty(kxRechargeRecord.getUserId())){
            ucid = ucid+"-u-"+kxRechargeRecord.getUserId().toString();
        }else {
            ucid = ucid+"-c-"+kxRechargeRecord.getCardId().toString();
        }
        int amountUpdate =  updateAccountAmount(kxRechargeRecord);//表示金额更新失败，再来一次
        if(amountUpdate==1){//金额更新成功，进行分账
            try {
                // 更新充值状态为交易完成
                KxRechargeRecord updateTranStatus = new KxRechargeRecord();
                updateTranStatus.setRechargeRecordId(kxRechargeRecord.getRechargeRecordId());
                updateTranStatus.setTranStatus(Constants.TranStatus.YES);
                kxRechargeRecordMapper.updateKxRechargeRecord(updateTranStatus);
                logger.info("用户/电卡: "+ucid+" 充值号: " + kxRechargeRecord.getRechargeRecordId() +
                        " 充值:"+ kxRechargeRecord.getBalance() + " 赠送: " + kxRechargeRecord.getGive() + " 成功");
                //开始分账逻辑，单独在线程中执行？或者再定时任务中处理？
//                splittingUserAmount(kxRechargeRecord);
                logger.info("用户/电卡: "+ucid+" 充值号: " + kxRechargeRecord.getRechargeRecordId() + " 分账成功");
            }catch (Exception e){
                // 此处添加上告警
                logger.error("用户/电卡: "+ucid+" 充值号: " + kxRechargeRecord.getRechargeRecordId() + " 分账失败 原因： "+ e.getMessage());
                e.printStackTrace();
            }
        }else{
            // 增加告警流程
            logger.error("用户/电卡: "+ucid+" 充值号: " + kxRechargeRecord.getRechargeRecordId() +
                    " 充值:"+ kxRechargeRecord.getBalance() + " 赠送: " + kxRechargeRecord.getGive() + " 更新余额失败");
            throw new UtilException("充值失败");
        }
    }

    // 更新用户，电卡余额
    private int updateAccountAmount(KxRechargeRecord kxRechargeRecord){
        if(ObjectUtils.isNotEmpty(kxRechargeRecord.getUserId())&&kxRechargeRecord.getUserId().longValue()!=0){
            //用户充值
            KxUserInfo kxUserInfo = kxUserInfoMapper.selectKxUserInfoByUserId(kxRechargeRecord.getUserId());
            kxUserInfo.setBalance(kxUserInfo.getBalance().add(kxRechargeRecord.getBalance()));
            kxUserInfo.setGive(kxUserInfo.getGive().add(kxRechargeRecord.getGive()));
            // 账户充值
            return kxUserInfoMapper.updateBalance(kxUserInfo);
        }else{// 电卡充值
            KxCard kxCard = kxCardMapper.selectKxCardByCardId(kxRechargeRecord.getCardId());
            kxCard.setBalance(kxCard.getBalance().add(kxRechargeRecord.getBalance()));
            kxCard.setGive(kxCard.getGive().add(kxRechargeRecord.getGive()));
            //电卡充值
            return kxCardMapper.updateBalance(kxCard);
        }

    }
}
